import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useEffect, useRef, useState, lazy, useImperativeHandle, } from "react";
import { LayoutB } from "~/public/cpas-ui";
import { Button, Checkbox } from "antd";
import { Progress } from "antd";
import { Dropdown, message, Space, Tooltip, Modal, Collapse, Spin, Input, Tree, } from "antd";
import "./_style.less";
import { getLeftTreeList, addTreeNodePage, delTreeNodePage, setEditTreeTittle, moveTreeNodePage, fetchReportList, getCpasTableName, editCpasTableNames, copyCpasTableFun, clearDataAll, queryDataState, queryResetState, queryVerifyStatezl, menuTemplateBatch, fetchAlwaysShow, getTemplateExportToSqlite, getNotesIsEmptyAPI, reCalculateNotesAPI, getAllVerifyTypeData, getSeekAuditReportTemplate, templateInitApi, getReportItemsZero, getTemplateInfo, singleDSTableInit, queryCpasTableByMb, clearFormulaAPI, fixDesignColumnCmapAPI, } from "../ExcelGrid/api/DesignTableApi";
import CpasIcon from "~/public/cpas-ui/components-ui/components/Icon";
import CpasTableDs from "../CpasTableDs";
import { CpasTableDsVariant } from "../CpasTableDs";
import ContextMenu from "devextreme-react/context-menu";
import TreeView from "devextreme-react/tree-view";
import Sortable from "devextreme-react/sortable";
import { getDataId } from "../../tools/Tools";
import { CheckOutlined, PlusOutlined, SaveOutlined, WarningOutlined, LoadingOutlined, } from "@ant-design/icons";
// import { dataMenu } from "./data"
// import {Popup,ToolbarItem} from "devextreme-react/popup"
import TemplateModal from "../../components-bs/components/TemplatePopup/ChangeTemplatePopup";
import TemplateSave from "../../components-bs/components/TemplatePopup/SaveTemplatePopup";
import { resetPidIfNotFound, EntrySynchronizationMethod, sortTreeByChildren, loopParentTreeList, getCurrentSysName, SystemName, getMergeType, MergeType, getHbTypeByZcbfid, } from "../../tools/Tools";
import notify from "devextreme/ui/notify";
import PageLoading from "./pageLoading";
import _ from "lodash";
import { E_CpasTableDescCategory } from "../CpasTableDs/CpasHandsonTableDs";
import { LoadPanel } from "devextreme-react/load-panel";
import ConfirmDialog from "./confirmDialog";
import { TextBox } from "devextreme-react/text-box";
import ImportExcelModal from "../CpasModal/ImportExcelModal";
import CpasModal from "../CpasModal";
import LogicPopup from "./draftPop";
import BuildLaction from "./noteBuildLocation";
import { saveTemplate,getTemplate } from '@/services/cpasRequest';


const Details = lazy(() => import("../ExcelGrid/components/Validator/CheckDetails"));
const { confirm } = Modal;
const { Search } = Input;
const { Panel } = Collapse;
const antIcon = _jsx(LoadingOutlined, { style: { fontSize: 15 }, spin: true });
//附注
export const NotePage = React.forwardRef((props, ref) => {
    const { businessName, initialState, dataMenu, dbname, renderRightDraw, dataId, tableAfterSelectionEndHook, rightMenuItem, renderDSLeftButton, renderDSRightButton, dbTableSaveSucces, dbTableSaveFail,bsdw } = props;
    const { zcbfid, zcbfName, sjxmbh, sjnd, AuditReportTemplate, curUser } = initialState?.curPart;
    const { usercode, username } = initialState?.curUser;
    const userInfoStr = window.localStorage.cpasUserInfo;
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {};
    const oringPassword = userInfo && userInfo.aesPassword
        ? userInfo.aesPassword
        : window.localStorage.aesPassword;
    const password = window["main"] && window["main"]["cryptoUtil"]
        ? window["main"]["cryptoUtil"](oringPassword)
        : "";
    const leftTreeRef = useRef();
    const dsTableRef = useRef();
    const dsRef = useRef();
    const templateRef = useRef(null);
    const saveRef = useRef(null);
    const importExcelRef = useRef(null);
    const exportRef = useRef(null);
    const curNodeRef = useRef();
    const lastCurNodeRef = useRef(); //用于记录上一次的节点
    const liftingNodeRef = useRef();
    const checkDetailModalRef = useRef();
    const [getTreesData, setTreesData] = useState([]);
    const [treeDataList, setTreeDataList] = useState([]);
    const [dataName, setDataName] = useState("");
    const [selectData, setSelectData] = useState({});
    const [copyItemData, setCopyItemData] = useState({});
    const [isModalOpen, setModalOpen] = useState(false);
    const [isShowOpen, setShowOpen] = useState(false);
    const initStateSize = ["22%", "20px", "80%"];
    const stateSize = ["40px", "40px", "40px"];
    const [isState, setIsState] = useState(true);
    const [isOpenEye, setOpenEye] = useState(true);
    const [allReportList, setAllReportList] = useState([]);
    const [dataSource, setDataSource] = useState([]);
    const [pageLoading, setPageLoading] = useState(false);
    const [disclosure, setDisclosure] = useState(false);
    const [includeTables, setIncludeTables] = useState(false);
    const [level, setLevel] = useState(false);
    const [optionsData, setOptionsData] = useState([]);
    const [value, setValue] = useState();
    const [projectName, setProjectName] = useState("");
    const [openDetails, setOpenDetails] = useState(false);
    const [verifyResult, setVerifyResult] = useState([]);
    const [clickItem, setClickItem] = useState({});
    const [noteProps, setNoteProps] = useState({});
    const [getDataIds, setDataIds] = useState(null);
    const [reportChecks, setReportChecks] = useState([]);
    const [popupShow, setPopupShow] = useState(false);
    const [templateModalShow, setTemplateModalShow] = useState(false);
    const [tableName, setTableName] = useState("");
    const [oldTableName, setOldTableName] = useState("");
    // const [importExcelModalShow, setImportExcelModalShow] = useState(false);
    const [importExcelList, setImportExcelList] = useState([]);
    const [menuItem, setMenuItem] = useState({
        isScree: false,
        isAlwaysShow: false,
        isCollapse: false, //菜单是否折叠
    });
    const [dbOrExcel, setDbOrExcel] = useState("");
    const [menuList, setMenuList] = useState([]);
    const [defaultCheckedKey, setDefaultCheckedKey] = useState([]);
    const [checkedAll, setCheckedAll] = useState(false);
    const [contentText, setContent] = useState(false);
    const [percentNum, setPercentNum] = useState(0);
    const [titleAndContent, setTitleAndContent] = useState({
        title: "",
        content: "",
    });
    // const [renameModal, setRenameModal] = useState<boolean>(false)
    const [dir, setDir] = useState("");
    const [showTemplateOpen, setShowTemplateOpen] = useState(false);
    const [contentMsg, setContentMsg] = useState("");
    const [btnLoading, setBtnLoading] = useState(false);
    const [btnLoadingId, setBtnLoadingId] = useState("");
    const [topIndex, setTopIndex] = useState(0);
    const [otherCheck, setOtherCheck] = useState(false);
    const [mainProject, setMainProject] = useState("");
    const { io } = require("socket.io-client");
    // lastScrollTop 用于记录上一次滚动条的位置
    const leftTreeScrollRef = useRef(0);
    const [loadingTimerId, setLoadingTimer] = useState(null);
    const [templateLoadPanelVisible, setTemplateLoadPanelVisible] = useState(false);
    //const [checkedNotesTids, setCheckedNotesTids] = useState<any>([]);
    const confirmDialogRef = useRef(); // 模板
    const [isSyncStatus, setIsSyncStatus] = useState("1"); // 1:初始化 2:进行中 3已完成
    const [searchValue, setSearchValue] = useState("");
    const [isRightTemplateAdd, setIsRightTemplateAdd] = useState(false); //是否是右键模版库添加
    const reportLocation = useRef(); // 报告位置
    const locationName = useRef(""); // 报告位置
    const draftRef = useRef(null);
    const isTodraft = useRef(null); // 是否是右键追加底稿
    const [isOpenWordlocation, setIsOpenWordlocation] = useState(false);
    const [searchTreesData, setSearchTreesData] = useState([]); //存储搜索状态下treeData的数据
    const [reportSearchValue, setReportSearchValue] = useState("");
    useEffect(() => {
        // 定义事件处理函数
        const handleCustomEvent = (event) => {
            console.log("Custom event received:", event.detail);
            // 在这里可以执行相应的操作，比如更新组件状态等
            setOpenDetails(false);
        };
        // 监听自定义事件
        document.addEventListener("closeDetail", handleCustomEvent);
        // 在组件卸载时移除事件监听器
        return () => {
            document.removeEventListener("closeDetail", handleCustomEvent);
        };
    }, []);
    // 获取年度值
    const getYearData = async () => {
        if (dataId) {
            setDataIds(dataId);
            return dataId;
        }
        else {
            const data = await getDataId();
            setDataIds(data);
            return data;
        }
    };
    const isOpenDraft = () => {
        if (isTodraft.current) {
            draftRef.current.show({
                title: "设置",
                dbname: dbname,
                zcbfid: zcbfid,
                sjxmbh: sjxmbh,
                username: username,
                dataId: dataId,
                okCallback: async (r, v) => {
                    // 调用底稿新增接口
                    // 阶段新增接口
                    isTodraft.current = false;
                },
            });
        }
    };
    const getCurrentMergeType = getMergeType();
    const isNeedBeforeData = getCurrentMergeType === MergeType.HB_HBYDT ||
        getCurrentMergeType === MergeType.HB_FD ||
        getCurrentMergeType === MergeType.DT_HBYDT
        ? true
        : false;
    const getCpasDescByCategory = (category, cpasDesc) => {
        if (!cpasDesc || cpasDesc.length === 0) {
            return null;
        }
        for (let i = 0; i < cpasDesc.length; i++) {
            const item = cpasDesc[i];
            if (item.category === category) {
                return item;
            }
        }
        return null;
    };
    useEffect(() => {
        const cpasApiUrl = localStorage.getItem("cpasApiUrl");
        const apiUrl = cpasApiUrl && cpasApiUrl.includes("cpasApi")
            ? cpasApiUrl.replace("/cpasApi", "")
            : cpasApiUrl;
        const socket = io(apiUrl, {
            connectionStateRecovery: {
                // the backup duration of the sessions and the packets
                maxDisconnectionDuration: 2 * 60 * 1000,
                // whether to skip middlewares upon successful recovery
                skipMiddlewares: true,
            },
            auth: {
                name: "notes",
            },
        });
        socket.on("connect", () => {
            const engine = socket.io.engine;
            console.log("socket connect: ", engine.transport.name); // in most cases, prints "polling"
            engine.on("close", (reason) => {
                // called when the underlying connection is closed
                console.log("socket close: ", reason);
            });
        });
        // either by directly modifying the `auth` attribute
        socket.on("connect_error", () => {
            console.log("connect_error 连接错误");
        });
        socket.io.on("reconnect_attempt", () => {
            console.log("reconnect_attempt 尝试重新连接");
        });
        socket.io.on("reconnect", () => {
            console.log("reconnect 尝试重新连接");
        });
        socket.on("disconnect", (reason) => {
            // ...
            console.log("disconnect 断开连接", reason);
        });
        socket.onAny((eventName, ...args) => {
            console.log(`on refresh onAny: ${eventName}`, args);
        });
        socket.on("notesSyncState", async (msg) => {
            console.log("on refresh ui event: ", msg);
            setIsSyncStatus("3");
            const res = msg ? JSON.parse(msg) : {};
            const args = res?.args || {};
            if (res.ok && (args?.tag === "note" || args?.tag === "singleNote")) {
                console.log("finish---loadingTimerId", loadingTimerId);
                clearTimeout(loadingTimerId);
                console.log(loadingTimerId, "loadingTimerId page");
                let params = {
                    dbname,
                    data_id: getDataIds,
                    type: "vr",
                };
                //跟兴哥聊的临时方案：单个同步找不到cpastable数据的情况下，需要执行节点删除操作。@小平那边单个同步远程没有数据时无法同时删除附注节点和cpastable数据的原因造成的
                if (args?.tag === "singleNote" && curNodeRef?.current?.fid) {
                    const tableData = await dsRef.current.loadTableByServer(curNodeRef.current.title, curNodeRef.current.dataId, curNodeRef.current.fid, null, isNeedBeforeData);
                    const msg = tableData.msg;
                    if (tableData?.code === 500 && msg && msg.includes("未找到该表")) {
                        message.warning(`${msg}~正在执行数据清理～`);
                        await deleteTreeFun(selectData.id, false);
                        await initReload();
                        dsRef.current.tableContentIsChange = false;
                        dsTableRef.current.zlTableRef.current.tableContentIsChange =
                            false;
                        setPageLoading(false);
                        return notify("同步成功", "success");
                    }
                }
                if (args?.tag === "singleNote" && curNodeRef?.current?.fid) {
                    params["tids"] = [curNodeRef.current.fid];
                }
                await getAllVerifyTypeData(params);
                await initReload(curNodeRef.current.title);
                setPageLoading(false);
                notify("同步成功", "success");
            }
            else {
                // clearTimeout(loadingTimerId);
                setPageLoading(false);
                notify("同步失败", "error", 2000);
            }
        });
        return () => {
            console.log("socket.clsoe log");
            clearTimeout(loadingTimerId);
            socket.close();
        };
    }, [getTreesData, loadingTimerId]);
    // useEffect(() => {
    //   console.log(isSyncStatus, "isSyncStatus----");
    //   if (isSyncStatus === "2") {
    //     setPageLoading(false);
    //   }
    // }, [isSyncStatus]);
    const paramItem = {
        dbName: dbname,
        disclosureGroup: "",
        disclosureContent: "",
        disclosureContentNote: "",
        associatedReport: "",
        lastYearCount: false,
        isEmpty: false,
        isVerified: false,
        isDisclosure: true,
        isIncludeTable: true,
        isZeroReportCount: false,
        isAlwaysShow: false,
        isSetLevel: true,
        isVerify: null,
        // title: "新建披露表"+ Math.round(Math.random()*10+50),
        icon: "icon-biaogeyangshiku",
        config: {},
        dataId: getDataIds,
    };
    // 初始化 默认选中第一条 加载第一条表格数据源
    // selTitle 指定选中的title数据
    const initReload = async (selTitle, templateType, isInitTemplate //是否是初始化模版调用
    // isClickIconVerify?: boolean //true的情况下是从左侧树节点点击的校验详情，防止接口重复加载
    ) => {
        const leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
        // 每次reload前记载一下上次的滚动条位置
        if (leftTreeViewScrollView) {
            leftTreeScrollRef.current = leftTreeViewScrollView.scrollTop();
        }
        setPageLoading(true);
        const dataId = await getYearData();
        const resData = await getLeftTreeList(dataId);
        // console.log(getTreesData, 'getTreesData initReload');
        if (resData.length > 0) {
            if (isInitTemplate) {
                setPercentNum(100);
            }
            const data = resetPidIfNotFound(resData);
            const dataTree = data.map((item) => {
                if (item.isAlwaysShow) {
                    defaultCheckedKey.push(item.id);
                    setDefaultCheckedKey([...defaultCheckedKey]);
                }
                const oldTree = getTreesData.filter((oldItem) => oldItem.fid === item.fid);
                // const oldParent = getTreesData.filter((oldItem: any) => oldItem.id ===item.pid );
                let isExpanded = false;
                if (localStorage.getItem("isExpanded") === "true" ||
                    (oldTree && oldTree[0]?.expanded)) {
                    isExpanded = true;
                }
                const obj = {
                    icon: "icon-biaogeyangshiku",
                    parentId: item.pid,
                    expanded: isExpanded,
                    key: item.title,
                    isDirectory: true,
                    ...item,
                };
                return obj;
            });
            if (defaultCheckedKey.length === dataTree.length) {
                setCheckedAll(true);
            }
            let selData = data[0];
            data.map((item) => {
                if (selTitle && item.title === selTitle) {
                    selData = item;
                }
                item.key = item.title;
            });
            setTreeDataList(data);
            setTreesData(dataTree);
            // let tableData;
            // if (!isClickIconVerify) {
            setSelectData(selData);
            const obj = {
                tid: selData.fid,
                data_id: selData.dataId,
            };
            setNoteProps(obj);
            curNodeRef.current = selData;
            const tableData = await dsRef.current.loadTableByServer(selData.title, selData.dataId, selData.fid, null, isNeedBeforeData);
            const verifyData = await dsRef.current.loadVerifyByServer(selData.fid + "-zl");
            console.log("初始化整理下的勾稽详情", verifyData);
            const titleName = selData.isIncludeTable ? (selData.title) : (_jsxs("div", { children: [selData.title, _jsx("span", { style: { color: "red" }, children: "(\u6B64\u62AB\u9732\u9879\u76EE\u4E0D\u5305\u542B\u8868\u683C)" })] }));
            setDataName(titleName);
            if (menuItem.isCollapse) {
                leftTreeRef?.current?.instance?.collapseAll();
            }
            // scrollToItem定位效果不佳
            if (selTitle) {
                setTimeout(() => {
                    const n_leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
                    n_leftTreeViewScrollView.scrollTo({
                        left: 0,
                        top: leftTreeScrollRef.current,
                    });
                }, 300);
                // leftTreeRef?.current?.instance?.scrollToItem(selData.id);
            }
            if (tableData?.code === 500) {
                setPageLoading(false);
                setBtnLoading(false);
                await dsRef.current.resetTable("ds");
                await dsTableRef.current.zlTableRef.current.resetTable("zl");
                return message.error(tableData.msg);
            }
            else {
                console.log(tableData, "tableData-----");
                await dsRef.current.reloadTable(tableData, null, null, true, true);
                const dc = getCpasDescByCategory(E_CpasTableDescCategory.DC, tableData.cpasDesc);
                const dcn = getCpasDescByCategory(E_CpasTableDescCategory.DCN, tableData.cpasDesc);
                dsTableRef.current.setTitleEditorContent(dc ? dc.describe : "");
                dsTableRef.current.setContentEditorContent(dcn ? dcn.describe : "");
                const zlParams = {
                    dbname,
                    tid: selData.fid,
                    type: "zl",
                };
                const lodaTableZl = await queryVerifyStatezl(zlParams);
                if (lodaTableZl.code === 200) {
                    dsTableRef.current.zlTableRef.current.setVerifyData(verifyData);
                    // try {
                    //   const result =
                    //     await dsTableRef.current.zlTableRef.current.articulationVerifyService.parseArtVerifyFormula(
                    //       dsTableRef.current.zlTableRef.current.articulationVerifyService
                    //         .artVerifyFormulaList,
                    //       dsRef.current
                    //     );
                    //   dsTableRef.current.zlTableRef.current.articulationVerifyService.artParseResultList =
                    //     result;
                    //   setVerifyResult(result);
                    // } catch (error) {
                    //   return message.error("勾稽计算错误！");
                    // }
                }
                const zlTableConfig = dsTableRef?.current?.zlTableRef?.current?.tableConfig;
                //整理模式配置信息初始化
                if (zlTableConfig) {
                    zlTableConfig.directionCfg = {
                        direction: "vertical",
                    };
                    const delTableCfg = [
                        "rowMergeCfg",
                        "filterCfg",
                        "sortCfg",
                        "hideColumnKeyArr",
                        "rule",
                    ];
                    for (let i = 0; i < delTableCfg.length; i++) {
                        if (zlTableConfig[delTableCfg[i]]) {
                            delete zlTableConfig[delTableCfg[i]];
                        }
                    }
                }
                console.log(zlTableConfig, "整理模式配置信息 zlTableConfig----");
                if (+dsTableRef?.current?.state?.tabValue === 2) {
                    dsTableRef.current.tabModelChanges("2");
                }
                setPageLoading(false);
            }
        }
        else {
            setDataName("");
            setBtnLoading(false);
            dsTableRef.current.setTitleEditorContent("");
            dsTableRef.current.setContentEditorContent("");
            setSelectData({});
            setNoteProps({});
            setTreesData([]);
            setPageLoading(false);
            const sysName = getCurrentSysName();
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            //去掉合并系统下，没有数据初始化模板的逻辑
            if (sysName !== SystemName.MERGE && templateType !== "switchTemplate") {
                initTemplate("");
            }
        }
    };
    // 自定义方法
    useImperativeHandle(ref, () => ({
        dsRef,
        selectData,
        dsTableRef,
        tab1Init: async () => {
            await initReload();
        },
        openVerifyDetail: (item, noVerifyModal) => {
            openDetail(null, item, noVerifyModal);
        },
        tab1SearchTableName(value, fid) {
            const currentData = getTreesData.filter((item) => item.fid === fid);
            if (currentData && currentData.length) {
                setSearchValue(currentData[0].title);
            }
            else {
                setSearchValue(value);
            }
        },
        //暴露保存双表方法
        dbTableSave: (data) => {
            dbTableSave(data);
        },
    }));
    const initContent = (param) => {
        setContent(param);
    };
    /**
     * 查询节点数据
     * @param isNoteSearch 是否是附注搜索调用
     * @returns
     */
    const getListsTree = async (isNoteSearch, currentSearchVal) => {
        const dataId = await getYearData();
        const leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
        // 每次reload前记载一下上次的滚动条位置
        if (leftTreeViewScrollView) {
            leftTreeScrollRef.current = leftTreeViewScrollView.scrollTop();
        }
        const resData = await getLeftTreeList(dataId);
        if (resData.length > 0) {
            const data = resetPidIfNotFound(resData);
            const dataTree = data.map((item) => {
                const oldTree = getTreesData.filter((oldItem) => oldItem.fid === item.fid);
                // const oldParent = getTreesData.filter((oldItem: any) => oldItem.id ===item.pid );
                let isExpanded = false;
                if (localStorage.getItem("isExpanded") === "true" ||
                    (oldTree && oldTree[0]?.expanded)) {
                    isExpanded = true;
                }
                const obj = {
                    parentId: item.pid,
                    expanded: oldTree && oldTree[0]?.expanded ? true : false,
                    key: item.title,
                    isDirectory: oldTree && oldTree[0]?.isDirectory ? true : false,
                    ...item,
                };
                return obj;
            });
            data.map((item) => {
                item.key = item.title;
            });
            console.log(data, "附注节点加载");
            const val = currentSearchVal ? currentSearchVal : searchValue;
            if (isNoteSearch && val) {
                return !isOpenEye && getTreesData && getTreesData.length
                    ? getTreesData
                    : dataTree;
            }
            else {
                setTreeDataList(data);
                setTreesData(dataTree);
                setTimeout(() => {
                    const n_leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
                    n_leftTreeViewScrollView.scrollTo({
                        left: 0,
                        top: leftTreeScrollRef.current,
                    });
                }, 300);
            }
        }
        // console.log(dbTable);
    };
    // 新增节点数据
    const newAddTreeNode = async (params) => {
        setPageLoading(true);
        const newTreeNode = await addTreeNodePage(params);
        if (newTreeNode.ok) {
            setCopyItemData({});
            setClickItem({});
            setPopupShow(false);
            setDir("");
            const obj = {
                tid: newTreeNode.data.fid,
                data_id: newTreeNode.data.dataId,
                status_name: "add",
            };
            setNoteProps(obj);
            const saveData = await dsTableRef.current.handleSaveData(newTreeNode.data.title, newTreeNode.data.fid, newTreeNode.data.dataId, "add");
            dsTableRef.current.setTitleEditorContent("");
            dsTableRef.current.setContentEditorContent("");
            if (saveData?.code) {
                return message.error(saveData.msg);
            }
            else {
                setSelectData(newTreeNode.data);
                setDataName(newTreeNode.data.title);
                curNodeRef.current = newTreeNode.data;
                const tableData = await dsRef.current.loadTableByServer(newTreeNode.data.title, newTreeNode.data.dataId, "ds", null, isNeedBeforeData);
                if (tableData?.code === 500) {
                    return notify(tableData.msg, "error", 2000);
                }
                else {
                    await dsRef.current.reloadTable(tableData, null, null, true, true);
                    setPageLoading(false);
                    getListsTree();
                    return notify("新增成功！", "success", 2000);
                }
            }
        }
        else {
            setClickItem({});
            setCopyItemData({});
            setPageLoading(false);
            setDir("");
            return notify(newTreeNode.msg, "error", 2000);
        }
    };
    // 修改节点数据
    const editTreeNodeItem = async (params) => {
        const editTittle = await setEditTreeTittle(params);
        if (editTittle.ok) {
            setDisclosure(params.isDisclosure);
            setLevel(params.isSetLevel);
            setPopupShow(false);
            setSelectData(params);
            initReload(curNodeRef?.current?.title);
            return notify("更新成功", "success", 2000);
        }
        else {
            console.log(editTittle);
            return notify("更新失败", "error", 2000);
        }
    };
    async function queryTable(params, isReloadTable) {
        const current = curNodeRef.current;
        const titleName = !current.isIncludeTable ? (_jsxs("div", { children: [params.title, _jsx("span", { style: { color: "red" }, children: "(\u6B64\u62AB\u9732\u9879\u76EE\u4E0D\u5305\u542B\u8868\u683C)" })] })) : (params.title);
        setDataName(titleName);
        const lodaTable = await dsRef.current.loadTableByServer(params.title, current.dataId, "ds", null, isNeedBeforeData);
        console.log("🚀 ~111 queryTable ~ lodaTable:", lodaTable)

        getTemplate(bsdw).then((ress) => {
            if(ress.data){
              saveTemplate({
                bsdwxydm:ress.data.bsdwxydm,
                reporttype: params.title,
                reportinfo: JSON.stringify(lodaTable), 
                mergeType: 2,
              }) 
            } 
          }) 


        const verifyData = await dsRef.current.loadVerifyByServer(current.fid + "-zl");
        // dsRef.current.setVerifyData(verifyData)
        dsTableRef.current.zlTableRef.current.setVerifyData(verifyData);
        const zlParams = {
            dbname,
            tid: current.fid,
            type: "zl",
        };
        const lodaTableZl = await queryVerifyStatezl(zlParams);
        if (lodaTableZl.code === 200) {
            getTreesData.map((item) => {
                if (item.id === params.id) {
                    item.isVerify = lodaTableZl.data;
                }
            });
            setTreesData(getTreesData);
            // setVerifyResult(verifyData.artParseResultList);
            try {
                const result = await dsTableRef.current.zlTableRef.current.articulationVerifyService.parseArtVerifyFormula(dsTableRef.current.zlTableRef.current.articulationVerifyService
                    .artVerifyFormulaList, dsTableRef.current.zlTableRef.current);
                dsTableRef.current.zlTableRef.current.articulationVerifyService.artParseResultList =
                    result;
                setVerifyResult(result);
            }
            catch (error) {
                return message.error("勾稽计算错误！");
            }
        }
        if (lodaTable?.code === 500) {
            setBtnLoading(false);
            setBtnLoadingId("");
            await dsRef.current.resetTable("ds");
            await dsTableRef.current.zlTableRef.current.resetTable("zl");
            return message.error(lodaTable.msg);
        }
        else {
            try {
                isReloadTable &&
                    (await dsRef.current.reloadTable(lodaTable, null, null, true, true));
                setBtnLoading(false);
                setBtnLoadingId("");
                setPopupShow(false);
            }
            catch (error) {
                setBtnLoading(false);
                console.log("表格加载出错了", error);
                return notify("加载出错了！", "error", 2000);
            }
        }
    }
    // 修改节点优化后
    const editTreeNode = async (params, isStopUpdateNotesTree, isReloadTable) => {
        let editTittle = {};
        if (!isStopUpdateNotesTree) {
            editTittle = await setEditTreeTittle(params);
        }
        const newId = editTittle?.data ? editTittle?.data : null;
         
        if (editTittle.ok || isStopUpdateNotesTree) {  
            setSelectData(params);
            if (params.isIncludeTable !== undefined) {
                getTreesData.map((item) => {
                    if (item.id === params.id) {
                        item.isIncludeTable = params.isIncludeTable;
                        if (newId) {
                            item.id = newId;
                            item.fid = newId;
                        }
                    }
                    if (item.pid === params.id && newId) {
                        item.pid = newId;
                    }
                });
                setIncludeTables(params.isIncludeTable);
            }
            else if (params.isDisclosure !== undefined) {
                getTreesData.map((item) => {
                    if (item.id === params.id) {
                        item.isDisclosure = params.isDisclosure;
                        if (newId) {
                            item.id = newId;
                            item.fid = newId;
                        }
                    }
                    if (item.pid === params.id && newId) {
                        item.pid = newId;
                    }
                });
            }
            else if (params.isSetLevel !== undefined) {
                getTreesData.map((item) => {
                    if (item.id === params.id) {
                        item.isSetLevel = params.isSetLevel;
                        if (newId) {
                            item.id = newId;
                            item.fid = newId;
                        }
                    }
                    if (item.pid === params.id && newId) {
                        item.pid = newId;
                    }
                });
            }
            else if (params.title !== undefined && params.fid === undefined) {
                getTreesData.map((item) => {
                    if (item.id === params.id) {
                        item.title = params.title;
                        item.dataId = params.Data_ID;
                        if (newId) {
                            item.id = newId;
                            item.fid = newId;
                        }
                    }
                    if (item.pid === params.id && newId) {
                        item.pid = newId;
                    }
                });
            }
            setTreesData([...getTreesData]);
            await queryTable(params, isReloadTable);
            if (newId) {
                params.id = newId;
                params.fid = newId;
            }
            setSelectData(params);
            return notify("更新成功！", "success", 2000);
        }
        else {
            return notify("更新失败！", "error", 2000);
        }
    };
    // 节点移动
    const moveNodeElement = async (params, id) => {
        setPageLoading(true);
        const moveNode = await moveTreeNodePage(params, id);
        if (moveNode.ok) {
            message.success("操作成功！");
            setPageLoading(false);
            getListsTree();
        }
        else {
            setPageLoading(false);
            message.error("操作失败！！！ 请稍后重试 ！");
        }
    };
    // 获取报表项目
    const getReportList = async (param) => {
        const params = {
            dbName: dbname,
            year: getDataIds,
        };
        const reportList = await fetchReportList(params);
        setModalOpen(param);
        if (!reportList.ok) {
            return message.error("暂无报表项目!!!");
        }
        else {
            const list = reportList.data.filter((item) => {
                item.key = item.itemName;
                item.title = item.itemName;
                item.children = reportList.data.filter((e) => {
                    e.key = e.itemName;
                    e.title = e.itemName;
                    return item.code === e.pCode;
                });
                return !item.pCode;
            });
            setAllReportList(list);
            return setDataSource(list);
        }
    };
    // 右键菜单 获取数据
    const treeViewItemContextMenu = (item) => {
        curNodeRef.current = item.itemData;
        liftingNodeRef.current = item;
        setDisclosure(curNodeRef.current.isDisclosure);
        setIncludeTables(curNodeRef.current.isIncludeTable);
        setLevel(curNodeRef.current.isSetLevel);
        setProjectName(curNodeRef.current.associatedReport);
        locationName.current =
            curNodeRef.current.location === null || curNodeRef.current.pid !== null
                ? ""
                : `附注${curNodeRef.current.location}`;
        locationName.current =
            curNodeRef.current.location === null || curNodeRef.current.pid !== null
                ? ""
                : `附注${curNodeRef.current.location}`;
        if (curNodeRef.current.associatedReport) {
            if (curNodeRef.current.associatedReport === "其它披露项目") {
                setOtherCheck(true);
                setReportChecks([]);
                setProjectName(curNodeRef.current.associatedReport);
            }
            else {
                const nodeArr = curNodeRef.current.associatedReport.split(",");
                setOtherCheck(false);
                setReportChecks(nodeArr);
                // setProjectName(curNodeRef.current.associatedReport)
            }
        }
    };
    const setNoteVerifyResult = function (result) {
        setVerifyResult(result);
    };
    // 右键操作 事件 优化修改 是否包含 表格
    const includeTableFun = () => {
        const paramData = curNodeRef.current;
        const params = {
            dbName: dbname,
            isIncludeTable: !paramData.isIncludeTable,
            id: paramData.id,
            title: paramData.title,
        };
        editTreeNode(params);
    };
    // 切换披露表
    const selectItem = async (e, isClickIconVerify) => {
        console.log("左键点击--节点选择", e);
        const currentSelData = e.itemData;
        /**
         * @return {
         * - 清除标记
         * - 设置整理tid dataId
         * - 当前选中值
         * - 不包含表格title 设置
         * - 获取表格 设置表格
         * }
         */
        if (e.itemData.id !== btnLoadingId) {
            console.warn("整理前后ref", dsTableRef, dsRef);
            console.log("是否弹出提示", dsRef.current.tableContentIsChange);
            setContent(false);
            setDir("sel");
            if (dsRef?.current?.tableContentIsChange ||
                dsTableRef?.current?.zlTableRef?.current?.tableContentIsChange) {
                confirm({
                    title: "提示",
                    icon: "",
                    content: "是否保存当前披露表内容？",
                    onOk() {
                        console.log("确认重置", dsRef.current.tableContentIsChange);
                        dsRef.current.tableContentIsChange = false;
                        dsTableRef.current.zlTableRef.current.tableContentIsChange =
                            false;
                        console.log("确认重置", dsRef.current.tableContentIsChange);
                        // eslint-disable-next-line @typescript-eslint/no-use-before-define
                        dbTableSave();
                    },
                    onCancel() {
                        // console.log('Cancel');
                        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
                        dsRef.current.tableContentIsChange = false;
                        dsTableRef.current.zlTableRef.current.tableContentIsChange =
                            false;
                        console.log("取消重置", dsRef.current.tableContentIsChange);
                    },
                });
            }
            else {
                setSelectData(e.itemData);
                setClickItem(e.itemData);
                curNodeRef.current = e.itemData;
                const obj = {
                    tid: e.itemData.fid,
                    data_id: e.itemData.dataId,
                };
                setNoteProps(obj);
                dsRef.current.articulationVerifyService.clearArtVerifyMark();
                setPageLoading(true);
                const titleName = !e.itemData.isIncludeTable ? (_jsxs("div", { children: [e.itemData.title, _jsx("span", { style: { color: "red" }, children: "(\u6B64\u62AB\u9732\u9879\u76EE\u4E0D\u5305\u542B\u8868\u683C)" })] })) : (e.itemData.title);
                setDataName(titleName);
                dsTableRef.current.zlTableRef.current.tableConfig = {};
                // getTreesData.map((c: any) => {
                //   if (e.itemData.id === c.id) {
                //     dsTableRef.current.setTitleEditorContent(c.disclosureContent)
                //     dsTableRef.current.setContentEditorContent(c.disclosureContentNote)
                //     dsTableRef.current.setTitleEditorPreviewContent(c.disclosureContent)
                //     dsTableRef.current.setContentEditorPreviewContent(c.disclosureContentNote)
                //   }
                // })
                if (e.itemData.id !== clickItem?.id) {
                    if (dsTableRef.current?.handleSetTabValue) {
                        dsTableRef.current?.handleSetTabValue();
                    }
                    dsTableRef.current.onShowBar();
                }
                // try {
                //     const result = await dsTableRef.current.zlTableRef.current.articulationVerifyService.parseArtVerifyFormula(dsTableRef.current.zlTableRef.current.articulationVerifyService
                //         .artVerifyFormulaList, dsRef.current);
                //     dsTableRef.current.zlTableRef.current.articulationVerifyService.artParseResultList =
                //         result;
                //     setVerifyResult(result);
                // }
                // catch (error) {
                //     return message.error("勾稽计算错误！");
                // }
                //切换节点前先重置一下当前表格状态
                await dsRef.current.resetTable();
                const lodaTable = await dsRef.current.loadTableByServer(e.itemData.title, e.itemData.dataId, "ds", null, isNeedBeforeData);
                console.log(lodaTable, "lodaTable----");
                const dc = getCpasDescByCategory(E_CpasTableDescCategory.DC, lodaTable.cpasDesc);
                const dcn = getCpasDescByCategory(E_CpasTableDescCategory.DCN, lodaTable.cpasDesc);
                dsTableRef.current.setTitleEditorContent(dc ? dc.describe : "");
                dsTableRef.current.setContentEditorContent(dcn ? dcn.describe : "");
                const verifyData = await dsRef.current.loadVerifyByServer(e.itemData.fid + "-zl");
                const zlParams = {
                    dbname,
                    tid: e.itemData.fid,
                    type: "zl",
                };
                const lodaTableZl = await queryVerifyStatezl(zlParams);
                if (lodaTableZl.code === 200) {
                    dsTableRef.current.zlTableRef.current.setVerifyData(verifyData);
                    // setVerifyResult(verifyData.artParseResultList);
                }
                console.log("wss获取整理下的", lodaTableZl);
                // setVerifyResult(verifyData.artParseResultList);
                if (lodaTable?.code === 500) {
                    setPageLoading(false);
                    await dsRef.current.resetTable("ds");
                    await dsTableRef.current.zlTableRef.current.resetTable("zl");
                    return message.error(lodaTable.msg);
                }
                else {
                    setPageLoading(false);
                    try {
                        await dsRef.current.reloadTable(lodaTable, null, null, true, true);
                        //从左侧校验详情iCON点击进入的话需要重算算一下校验结果数据@迁移至DS中整理模式更新校验结果setVerifyResult
                        // if (isClickIconVerify) {
                        //   try {
                        //     const result =
                        //       await dsTableRef.current.zlTableRef.current.articulationVerifyService.parseArtVerifyFormula(
                        //         dsTableRef.current.zlTableRef.current
                        //           .articulationVerifyService.artVerifyFormulaList,
                        //         dsRef.current
                        //       );
                        //     dsTableRef.current.zlTableRef.current.articulationVerifyService.artParseResultList =
                        //       result;
                        //     setVerifyResult(result);
                        //   } catch (error) {
                        //     return message.error("勾稽计算错误！");
                        //   }
                        // }
                    }
                    catch (error) {
                        console.info(error);
                        confirm({
                            title: "提示",
                            icon: "",
                            content: "当前披露表数据存在问题，请重新添加数据！",
                            async onOk() {
                                await dsRef.current.resetTable("ds");
                                await dsTableRef.current.zlTableRef.current.resetTable("zl");
                                dsRef.current.tableContentIsChange = false;
                                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                                dbTableSave(currentSelData);
                            },
                            onCancel() { },
                        });
                    }
                }
            }
        }
        else {
            return notify("请先等待保存完成后，再进行操作！", "error", 2000);
        }
    };
    /**
     *
     */
    const initByTemplate = async () => {
        const current = curNodeRef.current;
        const title = current.title;
        // const notes_tree_id = current.id;
        const electronParams = window.sessionStorage?.electronParams
            ? JSON.parse(window.sessionStorage.electronParams).params
            : {};
        let templateName = electronParams?.originGroupPart?.auditReportTemplate || "";
        let result;
        //兼容当前节点和右键选择的节点不同的情况下操作从模版初始化操作
        if (title !== selectData?.title) {
            await selectItem({
                itemData: curNodeRef.current,
            });
        }
        if (!templateName) {
            result = await getTemplateInfo(zcbfid);
        }
        const type = "ds";
        const dataId = await getDataId();
        const tableNames = [title];
        if (templateName || result?.ok) {
            if (!templateName && result?.data?.AuditReportTemplate) {
                templateName = result.data?.AuditReportTemplate;
            }
            const response_cpasData = await queryCpasTableByMb(dbname, templateName, tableNames, type);
            console.log(response_cpasData, "response_cpasData---");
            if (!response_cpasData.data) {
                return notify(`未在'${templateName}'模板中找到'${title}'披露表 , 因此未进行初始化`, "error", 4000);
                // return notify(`未找到该模板:${title}`, "info", 4000)
            }
            const response = await singleDSTableInit(dbname, templateName, tableNames, type, dataId);
            if (response.ok) {
                // const data = await getLeftTreeList(dbname, dataId);
                // setTreesData(dataTree)
                // setSelectData(curNodeRef.current);
                await initReload(curNodeRef.current.title);
                // leftTreeRef.current?.instance.selectItem(curNodeRef.current);
                //     await selectItem({
                //       itemData: curNodeRef.current,
                // });
                if (searchValue) {
                    onSearchValueChanged({
                        value: searchValue,
                    });
                }
                return notify(`${title}模板初始化成功`, "success", 4000);
            }
            else {
                return notify(response.msg, "error", 4000);
            }
        }
    };
    // 右键列表
    const menuItems = [
        {
            id: "不披露该附注",
            text: "不披露该附注",
            onItemClick: async () => {
                const paramData = curNodeRef.current;
                const params = {
                    dbName: dbname,
                    isDisclosure: !paramData.isDisclosure,
                    id: paramData.id,
                    title: paramData.title,
                };
                //  TODO
                editTreeNode(params);
            },
            icon: !disclosure,
        },
        {
            id: "不包含表格",
            text: "不包含表格",
            onItemClick: () => {
                includeTableFun();
            },
            icon: !includeTables,
        },
        {
            id: "不设级次",
            text: "不设级次",
            onItemClick: async () => {
                const paramData = curNodeRef.current;
                const params = {
                    dbName: dbname,
                    isSetLevel: !paramData.isSetLevel,
                    id: paramData.id,
                    title: paramData.title,
                };
                // TODO
                editTreeNode(params);
            },
            icon: !level,
        },
        {
            id: "报表项目",
            //text: `报表项目: ${projectName}`,
            text: (_jsx(Tooltip, { title: `报表项目: ${projectName}`, placement: "rightTop", children: `报表项目: ${projectName}` })),
            onItemClick: () => {
                getReportList(true);
                // setModalOpen(true)
            },
        },
        {
            id: "生成位置",
            text: (_jsx(Tooltip, { placement: "rightTop", children: `生成位置: ${locationName.current}` })),
            onItemClick: (e) => {
                if (curNodeRef.current.pid === null) {
                    setTimeout(() => {
                        setIsOpenWordlocation(true);
                    }, 500);
                    return true;
                }
                else {
                    message.error("只有顶级节点可以设置");
                }
            },
            // disabled: true
        },
        {
            id: "自定义添加",
            text: "自定义添加",
            items: [
                {
                    text: "上方添加",
                    onItemClick: () => {
                        setTimeout(() => {
                            setPopupShow(true);
                            setTableName("");
                            setDir("up");
                        }, 200);
                    },
                },
                {
                    text: "下方添加",
                    onItemClick: () => {
                        setTimeout(() => {
                            setPopupShow(true);
                            setTableName("");
                            setDir("down");
                        }, 200);
                    },
                },
                {
                    text: "子级",
                    onItemClick: () => {
                        setTimeout(() => {
                            setPopupShow(true);
                            setTableName("");
                            setDir("child");
                        }, 200);
                    },
                },
            ],
        },
        {
            id: "模板库添加",
            text: "模板库添加",
            onItemClick: _.debounce(async () => {
                // setIsRightTemplateAdd(true);
                setTemplateModalShow(true);
                const electronParams = window.sessionStorage?.electronParams
                    ? JSON.parse(window.sessionStorage.electronParams).params
                    : {};
                let templateName = electronParams?.originGroupPart?.auditReportTemplate || "";
                if (!templateName) {
                    let data = await getSeekAuditReportTemplate({ zcbfid });
                    if (data?.data?.AuditReportTemplate) {
                        templateName = data.data.AuditReportTemplate;
                    }
                }
                templateRef.current.showTemplate({ templateName });
            }, 100),
        },
        {
            id: "移动",
            text: "移动",
            items: [
                {
                    text: "上移",
                    onItemClick: async () => {
                        const childData = liftingNodeRef.current;
                        const dbData = curNodeRef.current;
                        if (childData.itemData.pid === null &&
                            childData.itemData.orderNo === 1) {
                            return message.warning("不可上移");
                        }
                        else if (childData.node.parent?.children[0].key === dbData.id) {
                            return message.warning("不可上移");
                        }
                        else {
                            const params = {
                                dbName: dbname,
                                target: {
                                    pid: dbData.parentId,
                                    orderNo: dbData.orderNo - 1,
                                },
                            };
                            moveNodeElement(params, dbData.id);
                        }
                    },
                },
                {
                    text: "下移",
                    onItemClick: async () => {
                        const dbData = curNodeRef.current;
                        const childData = liftingNodeRef.current;
                        const list = getTreesData.filter((item) => item.pid === null);
                        if (list[list.length - 1].id === dbData.id) {
                            return message.warning("不可下移");
                        }
                        else if (childData.node.parent?.children[childData.node.parent?.children.length - 1].key === dbData.id) {
                            return message.warning("不可下移");
                        }
                        else {
                            const params = {
                                dbName: dbname,
                                target: {
                                    pid: dbData.parentId,
                                    orderNo: dbData.orderNo + 1,
                                },
                            };
                            moveNodeElement(params, dbData.id);
                        }
                    },
                },
                {
                    text: "升级",
                    onItemClick: async () => {
                        const parentNode = liftingNodeRef.current;
                        if (parentNode.node.parent) {
                            const liftingPid = parentNode.node.parent?.parent
                                ? parentNode.node.parent?.parent.itemData.id
                                : null;
                            const params = {
                                dbName: dbname,
                                target: {
                                    pid: liftingPid,
                                    orderNo: parentNode.node.parent?.itemData.orderNo + 1,
                                },
                            };
                            moveNodeElement(params, liftingNodeRef.current.itemData.id);
                        }
                        else {
                            return message.error("不可升级");
                        }
                    },
                },
                {
                    text: "降级",
                    onItemClick: async () => {
                        const data = liftingNodeRef.current;
                        const current = curNodeRef.current;
                        console.log(data, current);
                        if (current.orderNo === 1) {
                            return message.warning("不可降级");
                        }
                        else {
                            console.log(getTreesData);
                            let nullIndex = 0;
                            const nodeNull = getTreesData.filter((item) => item.pid === current.pid);
                            nodeNull.map((m, index) => {
                                if (m.id === current.id) {
                                    nullIndex = index;
                                }
                            });
                            const nodeChild = getTreesData.filter((f) => nodeNull[nullIndex - 1].id === f.pid);
                            console.log(nodeChild);
                            const params = {
                                dbName: dbname,
                                target: {
                                    pid: nodeNull[nullIndex - 1].id,
                                    orderNo: nodeChild.length === 0
                                        ? 1
                                        : nodeChild[nodeChild.length - 1].orderNo + 1,
                                },
                            };
                            console.log(params);
                            moveNodeElement(params, current.id);
                        }
                    },
                },
            ],
        },
        {
            id: "删除",
            text: "删除",
            onItemClick: async () => {
                const current = liftingNodeRef.current;
                console.warn(current);
                deleteTreeFun(current.itemData.id);
            },
        },
        {
            id: "从模板初始化该表",
            text: "从模板初始化该表",
            onItemClick: async () => {
                await initByTemplate();
            },
        },
        {
            id: "重命名",
            text: "重命名",
            onItemClick: async () => {
                setTimeout(() => {
                    // eslint-disable-next-line @typescript-eslint/no-use-before-define
                    setPopupShow(true);
                    const current = curNodeRef.current;
                    setTableName(current.title);
                    setOldTableName(current.title);
                    setDir("rename");
                }, 500);
            },
        },
        {
            id: "复制",
            text: "复制",
            onItemClick: () => {
                const parentData = liftingNodeRef.current;
                setCopyItemData(parentData);
                return message.success("已复制");
            },
        },
        {
            id: "粘贴",
            text: "粘贴",
            onItemClick: async () => {
                const parentData = curNodeRef.current;
                if (!copyItemData.itemData) {
                    return message.warning("请先复制披露项目");
                }
                const upData = {
                    dbName: dbname,
                    ...copyItemData.itemData,
                    // eslint-disable-next-line @typescript-eslint/no-use-before-define
                    title: `${copyItemData.itemData.title}-副本${rand(1000, 9999)}`,
                    parentId: parentData.parentId,
                    pid: parentData.parentId,
                    orderNo: parentData.orderNo + 1,
                };
                const pasteNode = await addTreeNodePage(upData);
                if (pasteNode.ok) {
                    const pasteTable = await copyCpasTableFun({
                        dbname,
                        tid: copyItemData.itemData.fid,
                        grid_data_type: "source",
                        data_type: "json",
                        type: "ds",
                    });
                    if (pasteTable.ok) {
                        pasteTable.data.tableConfig = JSON.parse(pasteTable?.data.tableConfig);
                        const newTable = await dsRef.current.gridService.resetCpasTableId(pasteTable?.data);
                        await dsRef.current.reloadTable(newTable, null, null, true, true);
                        await dsTableRef.current.handleSaveData(pasteNode.data.title, pasteNode.data.fid, pasteNode.data.dataId);
                    }
                    getListsTree();
                    setCopyItemData({});
                    const { fid, title, dataId } = pasteNode.data;
                    selectItem({
                        itemData: {
                            ...upData,
                            title,
                            name: title,
                            key: title,
                            fid,
                            id: fid,
                            dataId,
                        },
                    });
                    return message.success("复制成功");
                }
                else {
                    setCopyItemData({});
                    return message.error(pasteNode.msg);
                }
            },
        },
    ];
    const getMenus = () => {
        if (rightMenuItem && rightMenuItem.length) {
            let menus = [];
            for (let i = 0; i < rightMenuItem.length; i++) {
                const id = rightMenuItem[i];
                const res = menuItems.filter((item) => item?.id === id);
                if (res && res.length) {
                    if (id === "报表项目") {
                        menus.push({
                            ...res[0],
                            onItemClick: () => { },
                        });
                    }
                    else {
                        menus.push({
                            ...res[0],
                        });
                    }
                }
            }
            return menus;
        }
        return menuItems;
    };
    // 随机数
    const rand = (max, min) => {
        return Math.floor(Math.random() * (max - min)) + min;
    };
    //
    // 生成位置点击事件
    let selectTitle = (e) => {
        let param = {
            dbName: dbname,
            id: curNodeRef.current.id,
            location: null,
        };
        if (e.itemData.selected) {
            param = {
                ...param,
                location: e.itemData.ID,
            };
        }
        reportLocation.current = param;
    };
    // tree 数据
    const newNodeTree = () => {
        const nodeTree = getTreesData.filter((item) => {
            delete item.children;
            item.children = getTreesData.filter((c) => {
                return c.pid === item.id;
            });
            return !item.pid;
        });
        return nodeTree;
    };
    function findNodeTree(tree, func) {
        for (const node of tree) {
            if (func(node))
                return node;
            if (node.children) {
                const result = findNodeTree(node.children, func);
                if (result)
                    return result;
            }
        }
        return null;
    }
    const deleteTreeFun = (child, isMessage = true) => {
        const newTree = newNodeTree();
        const fv = findNodeTree(newTree, (node) => {
            return node.id === child;
        });
        console.warn("找出的点", fv);
        deepLoop([fv], isMessage);
    };
    // 删除披露表增加递归循环
    const deepLoop = (node, isMessage = true) => {
        console.error("node", node);
        node.map(async (item) => {
            deepLoop(item.children, isMessage);
            if (isMessage) {
                const deleteTable = await dsTableRef.current.handleRemoveData(item.title, item.dataId);
                console.log("删除表格数据", deleteTable);
            }
            const delTree = await delTreeNodePage(item.id, dbname);
            if (delTree.ok && isMessage) {
                initReload(curNodeRef?.current?.title);
                return notify("披露项目已删除！", "success", 2000);
            }
            else if (isMessage) {
                return notify(delTree.ms, "error", 2000);
            }
            return;
        });
    };
    //  扩展 功能
    const menuItemFun = async (params) => {
        if (params === "synchronous") {
            const BusID = "附注";
            const tag = "note";
            setPageLoading(true);
            EntrySynchronizationMethod({
                usercode,
                password,
                zcbfid,
                BusID,
                tag,
            });
            clearTimeout(loadingTimerId);
            const timer = setTimeout(() => {
                notify("未收到同步结果", "error");
                setPageLoading(false);
            }, 120000);
            setLoadingTimer(timer);
            return;
        }
        setDbOrExcel(params);
        if (params === "template") {
            let data = await getSeekAuditReportTemplate({ zcbfid });
            console.log("当前模板：", data.data.AuditReportTemplate);
            const templateName = data.data.AuditReportTemplate;
            templateRef.current.showTemplate({ templateName });
        }
        else if (params === "isScree") {
            console.log(params, "params 筛选不勾稽项目", menuItem);
            if (menuItem.isScree) {
                initReload();
            }
            else {
                const screeTreeData = getTreesData.filter((item) => item.isVerify === false);
                const resTreeData = sortTreeByChildren(screeTreeData, treeDataList);
                setTreesData([...resTreeData]);
            }
        }
        else if (params === "isShow") {
            setMenuItem({
                ...menuItem,
                isAlwaysShow: true,
            });
            const dbTable = getTreesData.filter((item) => {
                if (item.isAlwaysShow) {
                    defaultCheckedKey.push(item.id);
                    setDefaultCheckedKey([...defaultCheckedKey]);
                }
                item.key = item.id;
                item.children = getTreesData.filter((child) => {
                    child.key = child.id;
                    return item.id === child.pid;
                });
                return !item.pid;
            });
            return setMenuList(dbTable);
        }
        else if (params === "templateSave") {
            saveRef.current.showTemplate();
        }
        else if (params === "reset") {
            confirmDialogRef.current.show({
                args: {
                    title: "批量重算",
                },
                okCallback: (r) => {
                    if (r) {
                        dsRef.current.hyperFormulaService.clearCache();
                        setPercentNum(0);
                        setInit(params);
                    }
                },
            });
        }
        else if (params === "clearFormula") {
            confirmDialogRef.current.show({
                args: {
                    title: "批量清空公式",
                },
                okCallback: (r) => {
                    if (r) {
                        dsRef.current.hyperFormulaService.clearCache();
                        setPercentNum(0);
                        batchClearFormula();
                    }
                },
            });
        }
        else if (params === "clearData") {
            // dsRef.current.hyperFormulaService.clearCache()
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            setPercentNum(0);
            setInit(params);
        }
        else if (params === "init") {
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            initTemplate("");
        }
        else if (params === "export") {
            exportRef.current.openExportDBDialog();
        }
        else if (params === "exportZLExcel" || params === "exportExcel") {
            exportRef.current.openExportExcelDialog(params);
        }
        else if (params === "exportZLExcelTodraft") {
            // 调用组件库里的函数exportZLExcelTodraft
            // 标记导出的表格为草稿
            isTodraft.current = true;
            exportRef.current.openExportExcelDialog(params);
        }
        else if (params === "import") {
            const successCallback = () => {
                initReload(curNodeRef?.current?.title);
            };
            exportRef.current.openImportDBDialog(successCallback);
        }
        else if (params === "importExcel") {
            importExcelRef.current.openImportDialog("附注");
        }
        else if (params === "break") {
            confirmDialogRef.current.show({
                args: {
                    title: "批量断开公式",
                },
                okCallback: async (r) => {
                    if (r) {
                        const batchParams = {
                            dbname,
                            data_id: getDataIds,
                            action: "off",
                        };
                        setPageLoading(true);
                        const batchClose = await menuTemplateBatch(batchParams);
                        setPageLoading(false);
                        if (batchClose.code === 200 && batchClose.ok) {
                            await initReload();
                            return notify("操作成功！", "success", 2000);
                        }
                        else {
                            return notify(batchClose.msg, "error", 2000);
                        }
                    }
                },
            });
        }
        else if (params === "restore") {
            confirmDialogRef.current.show({
                args: {
                    title: "批量恢复公式",
                },
                okCallback: async (r) => {
                    if (r) {
                        const batchParams = {
                            dbname,
                            data_id: getDataIds,
                            action: "on",
                        };
                        setPageLoading(true);
                        const batchOpen = await menuTemplateBatch(batchParams);
                        setPageLoading(false);
                        if (batchOpen.code === 200 && batchOpen.ok) {
                            await initReload();
                            return notify("操作成功！", "success", 2000);
                        }
                        else {
                            return notify(batchOpen.msg, "error", 2000);
                        }
                    }
                },
            });
        }
        else if (params === "excel") {
            setMenuItem({
                ...menuItem,
                exportOpen: true,
            });
        }
    };
    const items = dataMenu(leftTreeRef, menuItemFun, setMenuItem, menuItem);
    // 打开勾稽校验详情
    const openDetail = async (e, parentItem, noVerifyModal) => {
        console.log(parentItem, "parentItem---");
        parentItem.itemData = {
            ...parentItem,
        };
        curNodeRef.current = parentItem;
        // setSelectData(curNodeRef.current);
        //控制校验详情弹窗
        if (!noVerifyModal) {
            // 先通知其余校验详情进行关闭
            const customEvent = new CustomEvent("closeDetail", {
                detail: {
                    message: "close",
                },
            });
            document.dispatchEvent(customEvent);
            setTimeout(() => {
                // 等待自定义通知完成
                setOpenDetails(true);
            }, 50);
        }
        const obj = {
            tid: parentItem.fid,
            data_id: parentItem.dataId,
        };
        setSelectData(parentItem.itemData);
        setClickItem(parentItem.itemData);
        // await initReload(curNodeRef.current.title, "");
        // await initReload(curNodeRef.current.title, "", !noVerifyModal);
        // setNoteProps(obj)
        await selectItem(parentItem, true);
        await dsRef.current.articulationVerifyService.clearArtVerifyMark();
        console.log(dsTableRef?.current?.state?.tabValue, "dsTableRef?.current?.state?.tabValue-");
        // if (+dsTableRef?.current?.state?.tabValue === 1) {
        setTimeout(async () => {
            await dsTableRef.current.tabModelChanges("2");
        }, 80);
        // }
        if (e) {
            e.stopPropagation();
        }
    };
    // 关闭勾稽校验详情
    const closeDetail = () => {
        setOpenDetails(false);
    };
    const onDragChange = (e) => {
        if (e.fromComponent === e.toComponent) {
            const fromNode = findNode(getTreeView(e.fromData), e.fromIndex);
            const toNode = findNode(getTreeView(e.toData), calculateToIndex(e));
            if (toNode !== null && isChildNode(fromNode, toNode)) {
                e.cancel = true;
            }
        }
    };
    function findNode(treeView, formIndex) {
        const nodeElement = treeView
            .element()
            .querySelectorAll(".dx-treeview-node")[formIndex];
        if (nodeElement) {
            return findNodeById(treeView.getNodes(), nodeElement.getAttribute("data-item-id"));
        }
        return null;
    }
    function getTreeView(e) {
        return e === "driveC" ? leftTreeRef.current.instance : "";
    }
    function calculateToIndex(e) {
        if (e.fromComponent !== e.toComponent || e.dropInsideItem) {
            return e.toIndex;
        }
        return e.fromIndex >= e.toIndex ? e.toIndex : e.toIndex + 1;
    }
    function isChildNode(p, c) {
        let { parent } = c;
        while (parent !== null) {
            if (parent.itemData.id === p.itemData.id) {
                return true;
            }
            parent = parent.parent;
        }
        return false;
    }
    function findNodeById(node, id) {
        for (let i = 0; i < node.length; i += 1) {
            if (node[i].itemData.id === id) {
                return node[i];
            }
            if (node[i].children) {
                const nodes = findNodeById(node[i].children, id);
                if (nodes != null) {
                    return nodes;
                }
            }
        }
    }
    /**
     * @params { isDropInsideItem: false 同级节点调整 true 子级节点调整}
     */
    const moveNode = async (fromNode, toNode, isDropInsideItem) => {
        const params = {
            dbName: dbname,
            target: {},
        };
        console.log("拖动", fromNode, toNode, isDropInsideItem);
        if (fromNode?.key === toNode?.key) {
            // 当前节点移动
            return;
        }
        else if (toNode === null) {
            // 最后一个节点移动
            const parentList = getTreesData.filter((item) => item.pid === null);
            params.target = {
                pid: parentList[parentList.length - 1].pid,
                orderNo: parentList[parentList.length - 1].orderNo,
            };
        }
        else if (!isDropInsideItem && !toNode.parent) {
            params.target = {
                pid: toNode.parent,
                orderNo: toNode.itemData.orderNo,
            };
        }
        else if (!isDropInsideItem && toNode.parent) {
            params.target = {
                pid: toNode.parent.key,
                orderNo: toNode.itemData.orderNo,
            };
        }
        else {
            // 移动到子级
            if (toNode.children.length > 0) {
                const maxOrderNo = [];
                toNode.children.map((item) => {
                    maxOrderNo.push(item.itemData.orderNo);
                });
                params.target = {
                    pid: toNode.itemData.id,
                    orderNo: Math.max(...maxOrderNo) + 1,
                };
            }
            else {
                params.target = {
                    pid: toNode.itemData.id,
                    orderNo: 1,
                };
            }
        }
        setPageLoading(true);
        const moveNodeData = await moveTreeNodePage(params, fromNode.itemData.id);
        if (moveNodeData.ok) {
            setPageLoading(false);
            getListsTree();
            return message.success("更新成功");
        }
        else {
            setPageLoading(false);
            getListsTree();
            return message.success(moveNodeData.msg);
        }
    };
    const onDragEnd = (e) => {
        if (e.fromComponent === e.toComponent && e.formIndex === e.toIndex) {
            return;
        }
        const formTreeView = getTreeView(e.fromData);
        const toTreeView = getTreeView(e.toData);
        const fromNode = findNode(formTreeView, e.fromIndex);
        const toNode = findNode(toTreeView, calculateToIndex(e));
        if (e.dropInsideItem && toNode !== null && !toNode.itemData.isDirectory) {
            return;
        }
        moveNode(fromNode, toNode, e.dropInsideItem);
    };
    const itemTemplate = (m) => {
        const mergeType = getHbTypeByZcbfid();
        return (_jsx(React.Fragment, { children: _jsx(Spin, { spinning: m.id === btnLoadingId, indicator: antIcon, children: _jsxs("div", { className: `item-render ${m.id === curNodeRef.current.id ? "item-bg" : ""}`, children: [_jsxs("div", { className: "render-icon", style: { color: m.isEmpty ? "#999" : "none" }, children: [_jsx("span", { className: "icon-table", children: !m.isIncludeTable ? (_jsx(CpasIcon, { type: "icon-wubiaoge1", fontSize: 18 })) : (_jsx(CpasIcon, { type: m.icon, fontSize: 18 })) }), _jsx(Tooltip, { title: !m.isSetLevel ? m.title + "【不设级次】" : m.title, placement: "rightTop", children: m.title })] }), _jsx("span", { className: "render-span", children: mergeType === MergeType.TEMPLATE ||
                                m.isVerify === null ||
                                m.isVerify ||
                                m.isVerify === undefined ? ("") : (_jsx(WarningOutlined, { onClick: (e) => openDetail(e, m) })) })] }) }) }));
    };
    // 右键菜单 模板
    const menuTemplate = (t) => {
        return (_jsxs("div", { className: "menu-template", children: [_jsx("div", { className: "menu-icon", children: _jsx("span", { children: t.icon && _jsx(CheckOutlined, {}) }) }), _jsxs("div", { className: "menu-text-content", children: [" ", _jsx("span", { className: "menu-text", children: t.text }), t.items && _jsx("span", { className: "dx-menu-item-popout" }), " "] })] }));
    };
    const contextMenuItemClick = (e) => {
        if (e.itemData.onItemClick) {
            return e.itemData.onItemClick(e);
        }
    };
    const addNodeData = () => {
        setTableName("");
        setPopupShow(true);
        if (dir === "sel") {
            setDir("sel");
        }
        else {
            setDir("");
        }
    };
    // 显示隐藏报表为零的项目
    const checkTable = async () => {
        if (isOpenEye) {
            const dateId = getDataIds;
            const res = await getReportItemsZero({
                partId: zcbfid,
                dataId: dateId,
            });
            console.log(res, "查询报告基础数据为0的节点");
            const reportItemsZeroData = res && res.data ? res.data : null;
            let newTreesData = [];
            const delIds = [];
            for (let i = 0; i < getTreesData.length; i++) {
                const treeItem = getTreesData[i];
                if (reportItemsZeroData && reportItemsZeroData.length) {
                    for (let j = 0; j < reportItemsZeroData.length; j++) {
                        const reportItems = reportItemsZeroData[j];
                        if (treeItem.id === reportItems.id ||
                            treeItem.pid === reportItems.pid) {
                            delIds.push(treeItem.id);
                        }
                    }
                }
            }
            newTreesData = getTreesData.filter((item) => {
                return !delIds.includes(item.id);
            });
            console.log(newTreesData, "newTreesData 展示不为0的节点数据", delIds);
            setSearchTreesData(newTreesData);
            setTreesData(newTreesData);
        }
        else {
            getListsTree();
        }
    };
    useEffect(() => {
        if (isState && lastCurNodeRef.current) {
            curNodeRef.current = _.cloneDeep(lastCurNodeRef.current);
            lastCurNodeRef.current = null;
            leftTreeRef.current?.instance.selectItem(curNodeRef.current);
            console.log("🚀 ~ curNodeRef.current:", curNodeRef.current)
        }
    }, [isState]);
    useEffect(() => {
        setProjectName(curNodeRef.current.associatedReport);
    }, [selectData]);
    // 左侧 展开 收起
    const initPageCon = () => {
        return (_jsx(React.Fragment, { children: _jsx("div", { children: _jsx("i", { className: "icon-right block", onClick: () => {
                        if (!lastCurNodeRef.current) {
                            lastCurNodeRef.current = _.cloneDeep(curNodeRef.current);
                        }
                        setIsState(!isState);
                    } }) }) }));
    };
    // 执行双表保存
    const dbTableSave = async (currentSelData) => {
        setBtnLoading(true);
        setPageLoading(true);
        dsRef.current.tableContentIsChange = false;
        dsTableRef.current.zlTableRef.current.tableContentIsChange = false;
        // console.log("双表保存执行", dsRef.current.tableContentIsChange);
        // console.log("获取当前list", dsRef.current.articulationVerifyService.artVerifyFormulaList);
        const contentTitle = dsTableRef.current.getTitleEditorContent();
        const content = dsTableRef.current.getContentEditorContent();
        const displayData = dsRef.current?.hot.getData();
        const saveNotesData = currentSelData ? currentSelData : selectData;
        //获取整理下最新的content数据
        // let zlContent = content;  //默认等于设计模式下的数据
        // try {
        //   const zlContentNoteResponse = await parseFormulaByContentApi({
        //     content: content,
        //     displayData
        //   });
        //   if(zlContentNoteResponse.ok){
        //     zlContent = zlContentNoteResponse.data;
        //   }
        // }catch (e) {
        //   console.error(e);
        // }
        const params = {
            dbName: dbname,
            title: saveNotesData.title,
            id: saveNotesData.id,
            fid: saveNotesData.fid,
            // disclosureContentNote: content,
            // disclosureContent:contentTitle,
            // zlDisclosureContent:contentTitle,
            // zlDisclosureContentNote:zlContent,
        };
        setBtnLoadingId(saveNotesData.id);
        setTitleAndContent({
            ...titleAndContent,
            title: contentTitle,
            content: content,
        });
        console.log(selectData, "selectData 当前披露节点数据");
        const current = curNodeRef.current;
        const dbSave = await dsTableRef.current.handleSaveData(saveNotesData.title, saveNotesData.fid || current.fid, getDataIds);
        console.log("🚀 ~ dbTableSave ~ dbSave:", dbSave)
        try {
            const result = await dsTableRef.current.zlTableRef.current.articulationVerifyService.parseArtVerifyFormula(dsTableRef.current.zlTableRef.current.articulationVerifyService
                .artVerifyFormulaList, dsTableRef.current.zlTableRef.current);
            dsTableRef.current.zlTableRef.current.articulationVerifyService.artParseResultList =
                result;
            console.log(result);
        }
        catch (error) {
            notify(error, "error", 2000);
        }
        if (dbSave === "流程异常") {
            setBtnLoading(false);
            setBtnLoadingId("");
            setPageLoading(false);
            dbTableSaveFail && dbTableSaveFail();
            return;
        }
        // 更新注释内容，迁移到CpasTable内部处理
        if (dbSave === undefined) {
            editTreeNode(params, true);
        }
        const res = await getNotesIsEmptyAPI({
            dbName: dbname,
            dataId: saveNotesData.dataId,
            tid: current.id,
        });
        const isEmpty = res.ok && res.data ? res.data : false;
        console.log(isEmpty, "查询空披露表结果", current?.isEmpty);
        if (isEmpty !== current?.isEmpty) {
            await setEditTreeTittle({
                ...params,
                isEmpty,
            });
            await getListsTree(true);
            current.isEmpty = isEmpty;
            leftTreeRef?.current?.instance?.repaint();
        }
        setPageLoading(false);
        dbTableSaveSucces && dbTableSaveSucces();
    };
    const onSearchValueChanged = async (data) => {
        const val = data.value;
        if (val) {
            setSearchValue(val);
            const treesData = await getListsTree(true, val);
            if (!treesData) {
                return;
            }
            const currentTrees = treesData.filter((item) => item.title.includes(val));
            if (currentTrees && currentTrees.length) {
                const res = loopParentTreeList(currentTrees, treesData);
                setTreesData(res);
            }
        }
        else {
            if (!isOpenEye) {
                const data = searchTreesData && searchTreesData.length
                    ? searchTreesData
                    : getTreesData;
                setTreesData(data);
                setSearchValue("");
            }
            else {
                getListsTree();
                setSearchValue("");
            }
        }
    };
    // 右侧 表格
    const rightPageCon = () => {
        const rightProps = {
            title: dataName,
            type: "ds",
            name: dataName,
            dsRef: dsTableRef,
            ref: dsRef,
            notes: noteProps,
            initContent: initContent,
            contentText: contentText,
            itemName: projectName,
            onSynchronous: onSynchronous,
            afterSelectionEndHook: tableAfterSelectionEndHook,
            renderRightButton: renderDSRightButton,
            renderLeftButton: renderDSLeftButton,
            setNoteVerifyResult: setNoteVerifyResult,
        };
        const getCurrentMergeType = getMergeType();
        if (getCurrentMergeType === MergeType.HB_HBYDT ||
            getCurrentMergeType === MergeType.HB_FD ||
            getCurrentMergeType === MergeType.DT_HBYDT) {
            return (_jsxs(React.Fragment, { children: [_jsx(CpasTableDsVariant, { ...rightProps }), renderRightDraw && renderRightDraw()] }));
        }
        return (_jsxs(React.Fragment, { children: [_jsx(CpasTableDs, { ...rightProps }), renderRightDraw && renderRightDraw()] }));
    };
    const mergeType = getHbTypeByZcbfid();
    const renderPlus = () => {
        const isButton = mergeType === MergeType.UNKNOW || mergeType === MergeType.TEMPLATE; //报告系统和合并系统的编辑模版支持添加附注节点
        if (isButton) {
            return (_jsx("i", { children: _jsx(PlusOutlined, { onClick: () => addNodeData() }) }));
        }
    };
    // 左侧 披露表项目
    const leftPageCon = () => {
        return (_jsxs(React.Fragment, { children: [_jsxs("div", { className: "flexCon", children: [_jsx("div", { children: _jsx("i", { className: "icon-left block", onClick: () => {
                                    if (!lastCurNodeRef.current) {
                                        lastCurNodeRef.current = _.cloneDeep(curNodeRef.current);
                                    }
                                    setIsState(!isState);
                                } }) }), _jsxs("div", { className: "flex-start mr-8", children: [renderPlus(), mergeType === MergeType.TEMPLATE ? null : (_jsx(Tooltip, { title: isOpenEye ? "隐藏报表数为零的项目" : "显示报表数为零的项目", children: _jsx("i", { className: isOpenEye ? "icon-eye block" : "icon-eyes block", onClick: () => {
                                            setOpenEye(!isOpenEye);
                                            checkTable();
                                        } }) })), _jsx(Button, { type: "text", icon: _jsx(SaveOutlined, {}), onClick: () => dbTableSave(), loading: btnLoading }), _jsx(Dropdown, { menu: { items }, placement: "bottomLeft", arrow: true, trigger: ["click"], children: _jsx("a", { onClick: (e) => e.preventDefault(), style: { display: "inline-block", paddingTop: "5px" }, children: _jsx(Space, { children: _jsx("i", { className: "icon-list block" }) }) }) })] })] }), _jsxs("div", { className: "mt-8 table-sort left-page-con", style: { paddingRight: "10px" }, children: [_jsxs(Sortable, { filter: ".dx-treeview-item", group: "shared", data: "driveC", allowDropInsideItem: true, allowReordering: true, onDragChange: onDragChange, onDragEnd: onDragEnd, children: [_jsx(TextBox, { showClearButton: true, mode: "search", value: searchValue, onValueChanged: (e) => onSearchValueChanged(e) }), _jsx(TreeView, { id: "treeviewDriveC", 
                                    // searchEnabled={true}
                                    // searchValue={searchValue}
                                    // searchTimeout={300}
                                    // searchEditorOptions={{
                                    //   // value: searchValue,
                                    //   "valueChangeEvent": "change",
                                    //   "onValueChanged": onSearchValueChanged
                                    // }}
                                    expandedExpr: "expanded", dataStructure: "plain", ref: leftTreeRef, parentIdExpr: "parentId", 
                                    // dataSource={getTreesData}
                                    onItemClick: selectItem, displayExpr: "title", itemRender: itemTemplate, items: getTreesData, virtualModeEnabled: true, keyExpr: "id", onItemContextMenu: treeViewItemContextMenu })] }), _jsx("div", { className: "context-menu", children: _jsx(ContextMenu, { ref: curNodeRef, dataSource: getMenus(), target: "#treeviewDriveC .dx-treeview-item", onItemClick: contextMenuItemClick, itemRender: menuTemplate }) })] })] }));
    };
    // 确认披露表 名称
    const onConfirm = async () => {
        if (!tableName) {
            return notify("不能为空！", "error", 2000);
        }
        if (dir === "rename" && tableName === oldTableName) {
            setPopupShow(false);
            setTableName("");
            return;
        }
        const params = {
            dbname: dbname,
            tname: tableName,
            data_id: getDataIds,
            type: "ds",
        };
        const res = await getCpasTableName(params);
        if (res.code === 200 && res.data) {
            return message.warning("披露项目已存在");
        }
        if (dsTableRef.current?.handleSetTabValue) {
            dsTableRef.current?.handleSetTabValue();
        }
        const parentData = curNodeRef.current;
        await dsRef.current.resetTable("ds", true);
        await dsTableRef.current.zlTableRef.current.resetTable("zl", true);
        if (res.code === 200) {
            if (dir === "up") {
                const upData = {
                    pid: parentData.parentId,
                    orderNo: parentData.orderNo,
                    title: tableName,
                    ...paramItem,
                };
                console.log("up", upData);
                setTopIndex(liftingNodeRef.current.itemIndex);
                newAddTreeNode(upData);
                setTableName("");
            }
            else if (dir === "down") {
                const upData = {
                    pid: parentData.parentId,
                    orderNo: parentData.orderNo + 1,
                    title: tableName,
                    ...paramItem,
                };
                setTopIndex(liftingNodeRef.current.itemIndex);
                newAddTreeNode(upData);
                setTableName("");
            }
            else if (dir === "child") {
                const parentChild = liftingNodeRef.current;
                const upData = {
                    pid: parentData.id,
                    orderNo: null,
                    title: tableName,
                    ...paramItem,
                };
                const maxOrder = [];
                if (parentChild.node.children.length > 0) {
                    parentChild.node.children.map((item) => {
                        maxOrder.push(item.itemData.orderNo);
                    });
                    upData.orderNo = Math.max(...maxOrder) + 1;
                }
                else {
                    upData.orderNo = 1;
                }
                setTopIndex(liftingNodeRef.current.itemIndex);
                newAddTreeNode(upData);
                setTableName("");
            }
            else if (dir === "sel") {
                paramItem.pid = clickItem?.pid;
                paramItem.orderNo = clickItem?.orderNo + 1;
                paramItem.title = tableName;
                newAddTreeNode(paramItem);
                console.log("item", paramItem);
                setTableName("");
            }
            else if (dir === "") {
                const maxOrderNo = [];
                getTreesData.map((item) => {
                    if (item.pid === null) {
                        maxOrderNo.push(item.orderNo);
                    }
                });
                paramItem.pid = null;
                paramItem.orderNo =
                    maxOrderNo.length === 0 ? 1 : Math.max(...maxOrderNo) + 1;
                paramItem.title = tableName;
                console.log("=", paramItem);
                newAddTreeNode(paramItem);
                setTableName("");
            }
            else if (dir === "rename") {
                const current = curNodeRef.current;
                const p = {
                    dbname,
                    tid: current.fid,
                    name: tableName,
                    Data_ID: current.dataId,
                };
                const data = await editCpasTableNames(p);
                if (data?.ok) {
                    const param = {
                        dbName: dbname,
                        title: tableName,
                        Data_ID: current.dataId,
                        id: current.id,
                    };
                    await editTreeNode(param, false, true);
                }
                else {
                    return message.error("重命名失败");
                }
            }
        }
    };
    // 新增披露表项目名称
    const onChangeName = (e) => {
        const value = e.target.value ? e.target.value.trim() : "";
        console.log(value, "新增披露表项目名称");
        setTableName(value);
    };
    // menu菜单
    const onCheck = (val) => {
        console.log("点击显示当前值", val);
        const values = [...new Set(val.checked)];
        values.map((k) => {
            getTreesData.map((item) => {
                if (k === item.id) {
                    if (item.pid) {
                        if (values.indexOf(item.pid) === -1) {
                            values.push(item.pid);
                        }
                    }
                }
            });
        });
        if (values.length === getTreesData.length) {
            setCheckedAll(true);
        }
        else {
            setCheckedAll(false);
        }
        // // setCheckedKeys(val.checked)
        setDefaultCheckedKey(values);
    };
    // 常在界面显示
    const onOkConfirm = async () => {
        confirmDialogRef.current.show({
            args: {
                title: "常在界面展示",
                content: "警告！此行为同步后会覆盖其他成员的树形结构。",
            },
            okCallback: async (r) => {
                if (r) {
                    const dateId = getDataIds;
                    const params = {
                        dbName: dbname,
                        dataId: dateId,
                        ids: defaultCheckedKey,
                    };
                    const response = await fetchAlwaysShow(params);
                    if (response.ok) {
                        await getListsTree();
                        setMenuItem((menuItem.isAlwaysShow = !menuItem.isAlwaysShow));
                        return notify("更新成功！", "success", 2000);
                    }
                    else {
                        return notify("更新失败！", "error", 2000);
                    }
                }
            },
        });
        // defaultCheckedKey.map((item: any) => {
        //   getTreesData.map((t: any) => {
        //     if (item === t.id) {
        //       const params = {
        //         dbName: dbname,
        //         isAlwaysShow: true,
        //         id: item,
        //       }
        //       // TODO
        //       editTreeNodeItem(params)
        //     } else {
        //       const params = {
        //         dbName: dbname,
        //         isAlwaysShow: false,
        //         id: item,
        //       }
        //       // TODO
        //       editTreeNodeItem(params)
        //       setMenuItem(menuItem.isAlwaysShow = !menuItem.isAlwaysShow)
        //     }
        //   })
        // })
    };
    // 模板初始化@todo0524增加展示进度条操作。
    const initTemplate = async (data) => {
        // setShowTemplateOpen(true)
        const dateIds = await getDataId();
        setShowOpen(true);
        const res = await getSeekAuditReportTemplate({ zcbfid });
        console.log("🚀 ~ initTemplate ~ res:", res)
        if (res.success) {
            setPercentNum(0);
            const msg = data ? "正在进行切换模版~" : "正在进行模版初始化~";
            setContentMsg(msg);
            const resTemp = await templateInitApi({
                dbName: dbname,
                templateName: data ? data : res?.data?.AuditReportTemplate,
                tableNames: [],
                type: "ds",
                dataId: dateIds,
            });
            setPercentNum(30);
            if (resTemp.success) {
                //getListsTree()
                let params = {
                    dbname,
                    data_id: dateIds,
                    type: "vr",
                };
                await getAllVerifyTypeData(params);
                setPercentNum(60);
                await initReload("", "switchTemplate", true);
                if (+dsTableRef?.current?.state?.tabValue === 2) {
                    dsTableRef.current.tabModelChanges("1");
                }
                // setShowTemplateOpen(false)
                setContentMsg("");
                notify(`模板初始化成功`, "success", 2000);
                setShowOpen(false);
            }
            else {
                // setShowTemplateOpen(false);
                setPercentNum(100);
                setShowOpen(false);
                if (res?.data?.AuditReportTemplate || data) {
                    notify(`${resTemp.msg}`, "error", 2000);
                }
                else {
                    notify(`11请在首页组成部分信息内选择报告模板`, "warning", 2000);
                }
            }
        }
        else {
            // setShowTemplateOpen(false)
            setShowOpen(false);
            notify(`${res.data}`, "error", 2000);
        }
    };
    const onSearchTableName = (e) => {
        const newTreeData = getTreesData
            .filter((item) => item.title.includes(e.target.value))
            .filter((i) => {
            i.key = i.id;
            i.children = getTreesData.filter((child) => {
                child.key = child.id;
                return i.id === child.pid;
            });
            return !i.pid;
        });
        setMenuList(newTreeData);
    };
    const onSearchReportTableName = (e) => {
        const value = e.target.value;
        setReportSearchValue(value);
        if (value) {
            const loop = (data) => {
                let result = [];
                data.filter((item) => {
                    const { title, children } = item;
                    if (title.includes(value)) {
                        result.push({
                            ...item,
                            children: [],
                        });
                    }
                    if (children && children.length) {
                        const res = loop(children);
                        if (res && res.length) {
                            const pCode = res[0].pCode;
                            const isCode = result.filter((item) => item.code === pCode);
                            if (isCode && isCode.length) {
                                for (let i = 0; i < result.length; i++) {
                                    const { code } = result[i];
                                    if (code === pCode) {
                                        result[i].children = res;
                                    }
                                }
                            }
                            else {
                                result.push({
                                    ...item,
                                    children: res,
                                });
                            }
                        }
                    }
                });
                return result;
            };
            const newDataSource = loop(allReportList);
            setDataSource(newDataSource);
        }
        else {
            setDataSource(allReportList);
        }
    };
    /**批量清空公式 0510 */
    const batchClearFormula = async () => {
        setShowOpen(true);
        const clearParams = {
            dbname,
            data_id: getDataIds,
            cpasTableType: "ds",
        };
        let total = 0;
        const timer = setInterval(async () => {
            if (total < 100) {
                const res = await queryDataState({ type: "clearFormulas" });
                console.log(res);
                total = parseInt(res.data.process);
                setContentMsg(res.data.message);
                setPercentNum(total);
                if (res.ok && total === 100) {
                    await queryResetState({ process: 0, type: "clearFormulas" });
                    clearInterval(timer);
                }
            }
        }, 500);
        const res = await clearFormulaAPI(clearParams);
        if (res.ok) {
            setShowOpen(false);
            await initReload();
            return message.success("清空成功！");
        }
        else {
            setShowOpen(false);
            return message.success(res.msg);
        }
    };
    const setInit = async (params) => {
        setShowOpen(true);
        const clearDB = {
            dbname,
            data_id: getDataIds,
        };
        let total = 0;
        if (params === "reset") {
            await queryResetState({ process: 0, type: "verifyAndCalculate" }); //重置重算状态为0
            const timer = setInterval(async () => {
                if (total < 100) {
                    const res = await queryDataState({ type: "verifyAndCalculate" });
                    console.log(res);
                    total = parseInt(res.data.process);
                    setPercentNum(total);
                    setContentMsg(res.data.message);
                    if (res.ok && total === 100) {
                        await queryResetState({ process: 0, type: "verifyAndCalculate" });
                        clearInterval(timer);
                    }
                }
            }, 500);
            const data = await reCalculateNotesAPI(clearDB);
            if (data.ok) {
                await initReload();
                setShowOpen(false);
                return message.success("重算成功");
            }
            else {
                setShowOpen(false);
                return message.error(data.msg);
            }
        }
        else {
            const timer = setInterval(async () => {
                if (total < 100) {
                    const res = await queryDataState({ type: "clear" });
                    console.log(res);
                    total = parseInt(res.data.process);
                    setContentMsg(res.data.message);
                    setPercentNum(total);
                    if (res.ok && total === 100) {
                        await queryResetState({ process: 0, type: "clear" });
                        clearInterval(timer);
                    }
                }
            }, 500);
            const res = await clearDataAll(clearDB);
            if (res.ok) {
                setShowOpen(false);
                // lzx 取消清空数据后的批量重算
                // await getAllData({
                //   dbname,
                //   data_id: getDataIds,
                //   is_stop_rec: true,
                // })
                await initReload();
                return message.success("清空成功！");
            }
            else {
                setShowOpen(false);
                return message.success(res.msg);
            }
        }
    };
    const onChangeTreeShow = (e) => {
        if (e.target.checked) {
            getTreesData.map((item) => {
                return defaultCheckedKey.push(item.key);
            });
            setCheckedAll(true);
            setDefaultCheckedKey([...defaultCheckedKey]);
        }
        else {
            setDefaultCheckedKey([]);
            setCheckedAll(false);
        }
    };
    const onSynchronous = async () => {
        const BusID = curNodeRef.current.id;
        const tag = "singleNote";
        // let timer: any = null;
        setPageLoading(true);
        EntrySynchronizationMethod({
            usercode,
            password,
            zcbfid,
            BusID,
            tag,
            BusType: 101,
        });
        clearTimeout(loadingTimerId);
        const timer = setTimeout(() => {
            notify("同步失败! 请检查网络重试～", "error", 2000);
            setPageLoading(false);
        }, 15000);
        setLoadingTimer(timer);
        return;
    };
    useEffect(() => {
        initReload();
        getYearData();
    }, []);
    const setLoadingCallback = (value) => {
        console.log(value, "value---");
        setPageLoading(value);
    };
    const sysName = getCurrentSysName();
    return (_jsxs("div", { children: [_jsx(Spin, { spinning: pageLoading, children: _jsx("div", { className: "cpas-audit-ds-container", style: { height: "calc(100vh - 90px)", overflow: "auto" }, children: _jsx(LayoutB, { rowSize: isState ? initStateSize : stateSize, leftSlot: isState ? leftPageCon() : initPageCon(), rightSlot: rightPageCon() }) }) }), _jsx(CpasModal, { ref: exportRef, type: "ds", zcbfid: zcbfid, zcbfName: zcbfName, dsTableRef: dsTableRef, loadingCallback: setLoadingCallback, dataId: getDataIds, okCallback: isOpenDraft, importOkCallback: () => {
                    return initReload(curNodeRef?.current?.title);
                } }), _jsx(ImportExcelModal, { ref: importExcelRef, type: "ds", title: "\u5BFC\u5165Excel\u9644\u6CE8", loadingCallback: setLoadingCallback, dataId: getDataIds, okCallback: () => {
                    return initReload(curNodeRef?.current?.title);
                } }), _jsx(Modal, { title: "\u62A5\u8868\u9879\u76EE", open: isModalOpen, destroyOnClose: true, maskClosable: false, onCancel: () => {
                    setReportChecks([]);
                    setMainProject("");
                    setModalOpen(false);
                }, onOk: () => {
                    console.error(reportChecks);
                    const param = {
                        dbName: dbname,
                        associatedReport: reportChecks.join(","),
                        id: curNodeRef.current.id,
                        fid: curNodeRef.current.fid,
                        pid: curNodeRef.current.pid,
                        // title: curNodeRef.current.title
                    };
                    dsRef.current.props = {
                        ...dsRef.current.props,
                        itemName: reportChecks.join(","),
                    };
                    editTreeNodeItem(param);
                    setModalOpen(false);
                }, children: _jsx("div", { style: { height: "70vh" }, children: _jsxs(Collapse, { defaultActiveKey: ["1", "2"], expandIconPosition: "end", children: [_jsx(Panel, { header: "\u5176\u5B83\u9879\u76EE\u6CE8\u91CA", children: _jsxs("div", { style: {
                                        height: "50px",
                                        marginLeft: "15px",
                                        lineHeight: "50px",
                                    }, children: [_jsx(Checkbox, { onChange: (e) => {
                                                setReportChecks([]);
                                                setOtherCheck(e.target.checked);
                                                if (e.target.checked) {
                                                    setMainProject("disabled");
                                                    reportChecks.push("其它披露项目");
                                                    setReportChecks([...reportChecks]);
                                                }
                                                else {
                                                    setMainProject("");
                                                }
                                            }, checked: otherCheck }), " ", _jsx("span", { children: "\u5176\u5B83\u62AB\u9732\u9879\u76EE" })] }) }, "1"), _jsx(Panel, { header: "\u4E3B\u8981\u9879\u76EE\u6CE8\u91CA", collapsible: mainProject, children: _jsxs("div", { style: { height: "50vh", overflow: "auto" }, className: "report-modal-body", children: [_jsx(Search, { style: { marginBottom: 8, marginTop: 8 }, placeholder: "\u8BF7\u8F93\u5165\u8981\u67E5\u8BE2\u7684\u9879\u76EE\u540D\u79F0", onChange: onSearchReportTableName }), _jsx(Tree, { checkable: true, onCheck: (keys) => {
                                                setReportChecks(keys.checked);
                                            }, disabled: otherCheck, checkedKeys: reportChecks, treeData: dataSource, checkStrictly: true })] }) }, "2")] }) }) }), _jsx(Modal, { title: dir === "rename" ? "重命名" : "添加", open: popupShow, maskClosable: false, width: 380, onOk: () => onConfirm(), centered: true, destroyOnClose: true, onCancel: () => {
                    setPopupShow(false);
                    setTableName("");
                }, children: _jsxs("div", { className: "popup-name", children: [_jsx("span", { children: "\u62AB\u9732\u8868\u540D\u79F0: " }), _jsx(Input, { placeholder: "\u8BF7\u8F93\u5165\u62AB\u9732\u8868\u540D\u79F0", size: "middle", onChange: (e) => onChangeName(e), value: tableName })] }) }), _jsx(BuildLaction, { isOpenWordlocation: isOpenWordlocation, selectTitle: selectTitle, closeMadal: () => {
                    setIsOpenWordlocation(false);
                }, locationName: curNodeRef.current?.location ? curNodeRef.current.location : "", editTreeNodeItem: async () => {
                    await editTreeNodeItem(reportLocation.current);
                    setIsOpenWordlocation(false);
                } }), _jsxs(Modal, { open: menuItem.isAlwaysShow, title: "\u5E38\u5728\u754C\u9762\u5C55\u793A", destroyOnClose: true, maskClosable: false, onCancel: () => {
                    setDefaultCheckedKey([]);
                    setMenuItem((menuItem.isAlwaysShow = !menuItem.isAlwaysShow));
                }, onOk: () => onOkConfirm(), children: [_jsx("div", { className: "pro-search", children: _jsx(Search, { style: { marginBottom: 8 }, placeholder: "\u8BF7\u8F93\u5165\u8981\u67E5\u8BE2\u7684\u62AB\u9732\u8868\u540D\u79F0", onChange: onSearchTableName }) }), _jsxs("div", { className: "pro-list", children: [_jsx(Checkbox, { onChange: onChangeTreeShow, checked: checkedAll, children: "\u5168\u9009" }), _jsx(Tree, { checkable: true, onCheck: onCheck, checkedKeys: defaultCheckedKey, treeData: menuList, checkStrictly: true })] })] }), _jsx(Details, { isOpen: openDetails, handleOpen: closeDetail, params: dsTableRef, result: verifyResult, isBackAll: false, onBackAll: () => { } }), _jsx(TemplateModal, { ref: templateRef, title: templateModalShow ? "选择模板" : "切换模板", changeData: sysName === SystemName.MERGE
                    ? {
                        cloudTempType: "合并系统模板",
                    }
                    : {
                        cloudTempType: "报告模板",
                    }, okCallback: async (data) => {
                    console.log(data, "模板名称");
                    // 切换模版
                    if (!templateModalShow) {
                        initTemplate(data);
                        //右键模版库添加
                    }
                    else if (data) {
                        console.log(curNodeRef?.current?.title, "curNodeRef.current-----");
                        const successCallback = () => {
                            initReload(curNodeRef?.current?.title, "switchTemplate");
                        };
                        exportRef.current.confrimRightTemplateCallback(data, curNodeRef, successCallback);
                    }
                }, cancelCallback: () => {
                    if (templateModalShow) {
                        setTemplateModalShow(false);
                    }
                } }), _jsx(LoadPanel, { shadingColor: "rgba(0,0,0,0.4)", visible: templateLoadPanelVisible }), _jsx(TemplateSave, { ref: saveRef, 
                // saveData={{
                //   dbname,
                //   dateId: getDataIds || "",
                //   tableNames: [],
                //   type: "ds",
                // }}
                okCallback: async (data) => {
                    console.log(data, "data");
                    const params = {
                        dbName: dbname,
                        templateFile: "",
                        tableNames: [],
                        templateName: data,
                        type: "ds",
                        dataId: getDataIds,
                    };
                    // 设置loading为true
                    setTemplateLoadPanelVisible(true);
                    if (sysName !== SystemName.MERGE) {
                        try {
                            const res = await fixDesignColumnCmapAPI("ds");
                            if (!res.ok) {
                                setTemplateLoadPanelVisible(false);
                                return notify("脚本修复错误～", "error", 2000);
                            }
                        }
                        catch (e) {
                            setTemplateLoadPanelVisible(false);
                            return notify("脚本修复错误～", "error", 2000);
                        }
                    }
                    const resData = await getTemplateExportToSqlite(params);
                    console.log(resData, "resData----");
                    setTemplateLoadPanelVisible(false);
                    if (resData.code === 200) {
                        saveRef.current.reloadTemplate();
                        return notify("模板保存成功", "success", 2000);
                    }
                    else {
                        return notify(resData.msg, "error", 2000);
                    }
                }, changeData: sysName === SystemName.MERGE
                    ? {
                        cloudTempType: "合并系统模板",
                    }
                    : {
                        cloudTempType: "报告系统模板",
                    } }), _jsxs(Modal, { open: isShowOpen, footer: null, centered: true, maskClosable: false, closable: false, title: null, className: "dot-body", wrapClassName: "spin-example", children: [_jsx(Progress, { percent: percentNum, status: "active", style: { color: "#fff" } }), _jsx("div", { className: "process-content", children: contentMsg })] }), _jsx(PageLoading, { isOpen: showTemplateOpen, isMaskClose: false, content: "正在加载...", width: 200 }), _jsx(ConfirmDialog, { ref: confirmDialogRef }), _jsx(LogicPopup, { ref: draftRef, toolbarDisplay: false })] }));
});
export default NotePage;
